from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView

# Create your views here.
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework.views import APIView
from areas.models import Area
from areas.serializers import AreasSerializer, AddressSerializer


# 第二种把查询出来的数据放到redis中使用拓展类的方式
from users.models import Address


class AreasView(CacheResponseMixin, ListAPIView):

    # 获取所有省的信息
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):

    # 获取市的信息
    serializer_class = AreasSerializer
    # queryset = Area.objects.filter()

    # 当对数据库查询出来的数据进行缓存的时候,需要调用缓存装饰器
    # 参数timeout(保存时间),参数cache(缓存到哪个redis库中)
    # @cache_response(timeout=60*60, cache='areas')
    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView, UpdateAPIView, ListAPIView):

    # 保存地址
    serializer_class = AddressSerializer

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user, is_deleted=False)

    # 删除地址
    def delete(self, request, pk):

        # 获取对象
        obj = self.get_object()

        # 对象逻辑删除
        obj.is_deleted = True
        obj.save()

        return Response()

    # 展示保存的地址
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        # 由于返回的结果与前端接受的结果不一致,所有重写list方法
        return Response({'addresses': serializer.data, 'default_address_id': self.request.user.default_address_id})

    def put(self, request, *args, **kwargs):
            obj = self.get_object()
            obj.user.default_address_id = obj.id
            obj.user.save()
            return Response(status=200)


# 第一种获取默认地址的方法(通过地址对象获取用户对象)
# class AddressDefaultView(UpdateAPIView):
#
#     serializer_class = AddressSerializer
#
#     def get_queryset(self):
#         return Address.objects.filter(user=self.request.user, is_deleted=False)
#
#     # 设置默认地址
#     def put(self, request, *args, **kwargs):
#             obj = self.get_object()
#             obj.user.default_address_id = obj.id
#             obj.user.save()
#             return Response(status=200)

# 第二种方法直接重新写一个user对象的
# class AddressDefaultView(APIView):
    # def put(self, request, pk):
    #     user = self.request.user
    #     user.default_address_id = pk
    #     user.save()
    #     return Response(status=200)
